package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;

import com.itheima.pojo.Member;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;
    @Autowired
    private JedisPool jedisPool;

    //获得当前登录用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername(){
        //当Spring security完成认证后，会将当前用户信息保存到框架提供的上下文对象
        org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(user);
        if(user != null){
            String username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        }

        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }
    @PreAuthorize("hasAuthority('USER_ADD')")//新增用户权限
    @RequestMapping("/add")
    public Result add(@RequestBody User user, Integer[] roleIds) {

        BCryptPasswordEncoder encode = new BCryptPasswordEncoder();

        String password = encode.encode(user.getPassword());
        user.setPassword(password);

        try {
            userService.add(user, roleIds);
            return new Result(true, "新增用户成功");
        }  catch (RuntimeException e) {
            return new Result(false, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "新增用户失败");
        }
    }
    @PreAuthorize("hasAuthority('USER_QUERY')")//查询用户权限
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return userService.findPage(queryPageBean);
    }

    @RequestMapping("/findAll")
    public Result findAll() {
        List<User> all = userService.findAll();
        if (all != null && all.size() > 0) {
            return new Result(true, "查询用户成功", all);
        } else {
            return new Result(false, "查询用户失败");
        }
    }

    @RequestMapping("/findById")
    public Result findById(Integer userId) {
        try {
            User user = userService.findById(userId);
            user.setPassword(null);
            return new Result(true, "查询用户成功", user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询用户失败");
        }
    }

    @RequestMapping("/findRoleIdsByUserId")
    public Result findRoleIdsByUserId(Integer userId) {
        try {
            List<Integer> userIds = userService.findRoleIdsByUserId(userId);
            return new Result(true, "查询用户成功", userIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询用户失败");
        }
    }

    @PreAuthorize("hasAuthority('USER_EDIT')")//编辑用户权限
    @RequestMapping("/edit")
    public Result edit(@RequestBody  User user, Integer[] roleIds) {
        BCryptPasswordEncoder encode = new BCryptPasswordEncoder();
        if (user.getPassword()!=null){
            String password = encode.encode(user.getPassword());
            user.setPassword(password);
        }

        try {
            userService.edit(user, roleIds);
            return new Result(true, "编辑用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "编辑用户失败");
        }
    }

    @PreAuthorize("hasAuthority('USER_DELETE')")//删除用户权限
    @RequestMapping("/delete.do")
    public Result delete(Integer id) {
        try {
            userService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "删除用户失败");
        }
        return new Result(true, "删除用户成功");
    }

    @RequestMapping("/editPassword") //修改密码
    public Result editPassword(HttpServletResponse resp, @RequestBody Map userInfo) throws IOException {
        //从map中获取修改信息
        System.out.println("");
        String username = (String) userInfo.get("username");
        String password = (String) userInfo.get("password");
        String telephone = (String) userInfo.get("telephone");
        String validateCode = (String) userInfo.get("code");
        //从redis中取出保存的验证码
        Jedis jedis = jedisPool.getResource();
        String validateCodeInRedis = jedis.get(telephone + RedisMessageConstant.SENDTYPE_GETPWD);

        if (validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)) {
            //验证码校验成功,修改密码
            //加密密码
            BCryptPasswordEncoder encode = new BCryptPasswordEncoder();
            password = encode.encode(password);
            userService.editPassword(username,password);
            return new Result(true,null);
        } else {
            //验证码输入错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
